<?php

class DataGrabber_Cache
{
    protected $_folder = null;
    protected $_lifetime = null;
    
    public function __construct($folder = null, $lifetime = null) 
    {
        if ($folder) {
            $this->_folder = $folder;
        } else {
            $this->_folder = '../data/cache/';
        }
        
        if ($lifetime) {
            $this->_lifetime = $lifetime;
        } else {
             $this->_lifetime = (60 * 60 * 24 * 7);
        }
        
        $this->makeFolder();
    }
    
    public function get($key)
    {
        $filename = $this->getFilename($key);
        if (!file_exists($filename)) {
            return null;
        }
        
        // If the current time has passed the life time delete the cached version
        if ((filemtime($filename) + $this->_lifetime) < time()) {
            unlink($filename);
            return null;
        }
 
        return file_get_contents($filename);
    }
    
    public function put($key, $contents)
    {
        $filename = $this->getFilename($key);
        $result = file_put_contents($filename, $contents); 
        return $result !== false;
    }
    
    public function delete($key)
    {
        $filename = $this->getFilename($key);
        
        if (file_exists($filename)) {
            unlink($filename);
            return true;
        }
        
        return false;
    }
    
    protected function makeFolder() 
    {
        if (!is_dir($this->_folder)) {
            mkdir($this->_folder);
        }
        
        if (!is_writable($this->_folder)) {
            throw new Exception("Cache folder: " . $this->_folder . " is not writeable.");
        }
    }
    
    public function clear()
    {
        if (is_dir($this->_folder)) {
            rmdir($this->_folder);
            $this->makeFolder();
        }
    }
    
    protected function getFilename($key)
    {
        return $this->_folder . '/' . md5($key);
    }
}
